<template>
  <div class="container">
    <navBar
      :title="'审批流程'"
      :query="queryData"
      :backStep="'myToDoList'"
    ></navBar>
    <topForm :code="code" :formInfoObj="formInfoObj" :wordId="wordId"></topForm>
    <topForm2
      :code="code"
      :formInfoObj="formInfoObj"
      :wordId="wordId"
    ></topForm2>
    <div class="workTitle">审批流程</div>

    <div class="formBox">
      <div class="formItem">
        <div class="cellCss">
          <div class="cellCssContent">
            <div class="left">{{ nodeName }}:</div>
            <div class="right">{{ approverName }}</div>
          </div>
          <div class="cellCssContent">
            <div class="left">审批意见：</div>
            <div class="right">
              <van-radio-group v-model="radio" direction="horizontal">
                <van-radio name="1">同意</van-radio>
                <van-radio name="0">不同意</van-radio>
              </van-radio-group>
            </div>
          </div>
          <div class="confirmBox">
            <div class="confirmTop">
              <img :src="submitPic3" alt="" />
              <div class="confirmBtn" @click="goSignature">确认签字</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <van-goods-action>
      <van-goods-action-button
        :style="{
          background: '#0077FF',
          color: '#fff',
        }"
        type="danger"
        text="提交"
        :disabled="upBtn"
        @click="onClickButton"
      />
    </van-goods-action>
    <van-popup
      v-model="showSignature"
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div class="sign-finish">
        <div class="wrap">
          <div class="actionsWrap">
            <div class="actions">
              <van-button type="primary" @click="handleClear">清除</van-button>
              <van-button
                class="action-button"
                type="warning"
                @click="showSignature = false"
                >退出</van-button
              >
              <van-button
                class="action-button"
                type="info"
                @click="handlePreview"
                >保存</van-button
              >
            </div>
          </div>
          <canvas class="canvas" ref="canvas" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getTicketDetailApi, approveApi } from '@/api/ticket'
import { uploadApi } from '@/api/index'
import topForm2 from './components/topForm2'

import '@/css/form.scss'
import SmoothSignature from 'smooth-signature'
import navBar from '@/components/navBar.vue'
import topForm from './components/topForm'
export default {
  name: 'approveWork',
  props: {},
  components: { navBar, topForm, topForm2 },
  data() {
    return {
      showSignature: false,
      signatureBase64: null,
      signature: null,
      radio: '1',
      formInfoObj: {},
      isLoginMsg: {},
      submitPic1: null,
      submitPic2: null,
      submitPic3: null,
      nowPic: '',
      nodeName: '',
      approverName: '',
      approverId: '',
      upBtn: false,
      queryData: {
        activeIndex: 1,
      },
    }
  },
  created() {
    this.wordId = this.$route.query.id
    this.code = this.$route.query.code
    this.codeName = this.$route.query.codeName
    this.nodeName = this.$route.query.nodeName
    this.approverName = this.$route.query.approverName
    this.approverId = this.$route.query.approverId
    this.getOneApi()
    this.isLoginMsg = JSON.parse(sessionStorage.getItem('loginInfo'))
  },
  methods: {
    async onClickButton() {
      this.upBtn = true
      const data = {
        ticketId: this.formInfoObj.id,
        signature: this.submitPic3,
        userId: this.approverId,
        status: this.radio,
      }

      const res = await approveApi(data)
      console.log(res)
      if (res.code == 0) {
        this.upBtn = false

        this.$router.push({
          path: '/myToDoList',
        })
      }
    },
    goSignature() {
      this.showSignature = true
      this.handleSignature()
    },
    handleSignature() {
      this.signatureBase64 = ''
      this.$nextTick(() => {
        const canvas = this.$refs['canvas']
        const options = {
          width: window.innerWidth - 120,
          height: window.innerHeight - 80,
          minWidth: 3,
          maxWidth: 10,
          openSmooth: true,
          bgColor: '#f6f6f6',
        }
        this.signature = new SmoothSignature(canvas, options)
      })
    },
    handleClear() {
      this.signature.clear()
    },
    async handlePreview() {
      const isEmpty = this.signature.isEmpty()
      if (isEmpty) {
        return
      }
      const canvas = this.signature.getRotateCanvas(-90)
      const pngUrl = canvas.toDataURL('image/png')
      this.signatureBase64 = pngUrl

      // 转换为File对象
      const file = this.base64ToFile(pngUrl, `signature_${Date.now()}.png`)

      const formData = new FormData()
      formData.append('file', file)

      try {
        const res = await uploadApi(formData)

        this.submitPic3 = res.data
      } catch (err) {
        this.$toast('上传失败，请重试')
      }

      this.showSignature = false
    },
    base64ToFile(base64Data, filename) {
      const arr = base64Data.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }

      return new File([u8arr], filename, { type: mime })
    },
    async getOneApi() {
      const res = await getTicketDetailApi({ id: +this.wordId })
      this.formInfoObj = res.data
    },
  },
  mounted() {},
  watch: {},
  computed: {},
  filters: {},
}
</script>

<style scoped lang="scss">
.container {
  background-color: #f5f6f7;
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  padding-bottom: 60px;
}

.confirmBox {
  margin-top: 10px;
  .confirmTop {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .confirmBtn {
    width: 60px;
    height: 28px;
    text-align: center;
    line-height: 28px;
    border: 1px solid #dbe0e7;
    padding: 2px 6px;
    border-radius: 4px;
  }
  img {
    width: 150px;
    height: 50px;
  }
}

.sign-finish {
  width: 100vw;
  height: 90vh;
  canvas {
    border-radius: 10px;
    border: 2px dashed #ccc;
    width: 100px;
    height: 90vh;
  }
  .wrap {
    padding: 15px;
    height: 100%;
    display: flex;
    justify-content: center;
    .actionsWrap {
      width: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .canvas {
      flex: 1;
    }
    .actions {
      margin-right: 10px;
      white-space: nowrap;
      transform: rotate(90deg);
      .action-button {
        margin-left: 15px;
      }
    }
  }
}
</style>
